package dfs;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
//todo
public class ColoringABorder1034 {
    int[][] direc = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

    public int[][] colorBorder(int[][] grid, int row, int col, int color) {
        int target = grid[row][col];
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                boolean draw = false;
                if (grid[i][j] == target) {
                    for (int k = 0; k < direc.length; k++) {
                        int x = i + direc[k][0];
                        int y = j + direc[k][1];
                        if (x < 0 || x >= grid.length || y < 0 || y >= grid[0].length) {
                            draw = true;
                        }
                    }
                    if (!draw) {
                        for (int k = 0; k < direc.length; k++) {
                            if (grid[i + direc[k][0]][j + direc[k][1]] != target &&grid[i + direc[k][0]][j + direc[k][1]] !=-1){
                                draw = true;
                            }
                        }
                    }

                }
                if(draw){
                    grid[i][j] = -1;
                }
            }

        }

        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if(grid[i][j]==-1){
                    grid[i][j] = color;
                }
            }
        }


        return grid;
    }

//    public int[][] colorBorder(int[][] grid, int row, int col, int color) {
//        int m = grid.length, n = grid[0].length;
//        boolean[][] visited = new boolean[m][n];
//        List<int[]> borders = new ArrayList<>();
//        int originalColor = grid[row][col];
//        visited[row][col] = true;
//        dfs(grid, row, col, visited, borders, originalColor);
//        for (int i = 0; i < borders.size(); i++) {
//            int x = borders.get(i)[0], y = borders.get(i)[1];
//            grid[x][y] = color;
//        }
//        return grid;
//    }
//
//    private void dfs(int[][] grid, int x, int y, boolean[][] visited, List<int[]> borders, int originalColor) {
//        int m = grid.length, n = grid[0].length;
//        boolean isBorder = false;
//        int[][] direc = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
//        for (int i = 0; i < 4; i++) {
//            int nx = direc[i][0] + x, ny = direc[i][1] + y;
//            if (!(nx >= 0 && nx < m && ny >= 0 && ny < n && grid[nx][ny] == originalColor)) {
//                isBorder = true;
//            } else if (!visited[nx][ny]) {
//                visited[nx][ny] = true;
//                dfs(grid, nx, ny, visited, borders, originalColor);
//            }
//        }
//        if (isBorder) {
//            borders.add(new int[]{x, y});
//        }
//    }

}
